// 服务端
const fs = require('fs')
const express = require('express')
const Vue = require('vue')

// 创建渲染器
// const renderer = require('vue-server-renderer').createRenderer()
const { createBundleRenderer } = require('vue-server-renderer')
const serverBundle = require('../../dist/server/vue-ssr-server-bundle.json')
const clientManifest = require('../../dist/client/vue-ssr-client-manifest.json')
const renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false, // 宿主上下文
    template: fs.readFileSync('../../public/index.temp.html', 'utf-8'),
    clientManifest
})

// 创建 express 和 vue 实例
const app = express()

// 中间价处理静态文件请求
// 第二个参数的 index: false 一定要设置
app.use(express.static('../../dist/client', { index: false }))

const page = new Vue({
    data() {
        return {
            title: 'ssr 变量'
        }
    },
    template: '<div><h1>{{title}}</h1><div>hello vue ssr</div></div>'
})

app.get('*', async (req, res) => {
    try {
        const context = {
            url: req.url,
            title: 'ssr test'
        }
        const html = await renderer.renderToString(context)
        console.log(html);
        res.send(html)
    } catch (error) {
        res.status(500).send('服务端错误')
    }
})

// 启动服务
app.listen('8080', () => {
    console.log('服务启动')
})
